package org.nf.web.param;

import cn.hutool.core.util.ReflectUtil;
import org.nf.web.annotation.Model;
import org.nf.web.common.TypeConverter;
import org.nf.web.servlet.MethodArgumentsResovler;
import org.nf.web.servlet.ServletApi;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Parameter;
import java.util.ServiceLoader;

/**
 * @Author lzp
 * @Date 2024-05-17
 * 对象参数解析器
 */
public class ModelMethodArgumentResolver implements MethodArgumentsResovler {

    private final ServiceLoader<TypeConverter> LOADER =
            ServiceLoader.load(TypeConverter.class);

    @Override
    public boolean suppots(Parameter parameter) {
        return parameter.isAnnotationPresent(Model.class);
    }

    @Override
    public Object resolve(Parameter parameter, ServletApi servletApi) {
        //获取参数的calss类型
        Class<?> modelType = parameter.getType();
        Object entity = ReflectUtil.newInstance(modelType);
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(modelType, Object.class);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor pd : propertyDescriptors){
                String name = pd.getName();
                Object value = servletApi.request().getParameter(name);
                if (value != null){
                    ReflectUtil.invoke(entity,pd.getWriteMethod(),value);
                }
            }
            return entity;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }
}
